//
//  HRZUserManager.m
//  EMarket
//
//  Created by 石头 on 2018/10/9.
//  Copyright © 2018 好日子. All rights reserved.
//

#import "HRZUserManager.h"
// Controllers

// Models

// Views

// Vendors
#import <YYKit/YYCache.h>
// Categories
#import <NSObject+YYModel.h>
// Others
#import "HRZAuthorService.h"

@implementation HRZUserManager

SINGLETON_FOR_CLASS(HRZUserManager)

#pragma mark - ----  注册  ----
- (void)userReciveVerifyNumBySendPhoneNumber:(NSString *)phoneNum {
        //  发送手机号，获取注册码
}

- (void)userRegisterByPhone:(NSString *)phone password:(NSString *)password verifyNum:(nonnull NSString *)verifyNum completion:(nonnull loginBlock)completion {
    
    [HRZAuthorService userRegisterWithPhoneNum:phone verityNum:verifyNum password:password success:^(NSString *suc) {
        
        completion(YES, suc);
        
    } failure:^(NSString *err) {
        
        completion(NO, err);
        
    }];
}

#pragma mark - ----  三方登录  ----
- (void)loginWithThirdType:(UserLoginType)loginType complete:(loginBlock)complete {
    
}

#pragma mark - ----  账户登录  ----
- (void)loginWithUsername:(NSString *)username password:(NSString *)password completion:(loginBlock)completion {
    
    WEAKSELF
    [HRZAuthorService userLoginWithUserAccount:username password:password phoneId:@"123123" success:^(HRZUserInfo *userInfo) {
    
        weakSelf.curUserInfo = userInfo;
        [weakSelf saveUserInfo];
        completion(YES, @"");
        KPostNotification(KNotificationLoginStateChange, @YES);
        
    } failure:^(NSString *err) {
        completion(NO, err);
    }];
}

#pragma mark - ----  自动登录  ----
- (void)autoLoginToServer:(loginBlock)completion {
    
}

#pragma mark - ----  用户登出  ----
- (void)logout:(loginBlock)completion {
    
    self.curUserInfo = nil;
    self.isLogined = NO;
    
    YYCache *cache = [[YYCache alloc] initWithName:KUserCacheName];
    [cache removeAllObjectsWithBlock:^{
        if (completion) {
            completion(YES, nil);
        }
    }];
    
    KPostNotification(KNotificationLoginStateChange, @NO);
}

#pragma mark - ----  存储用户  ----
- (void)saveUserInfo {
    if (self.curUserInfo) {
        YYCache *cach = [[YYCache alloc] initWithName:KUserCacheName];
        NSDictionary *userDic = [self.curUserInfo modelToJSONObject];
        [cach setObject:userDic forKey:KUserModelCache];
    }
}

#pragma mark - ----  加载用户  ----
- (BOOL)loadUserInfo {
    YYCache *cache = [[YYCache alloc] initWithName:KUserCacheName];
    NSDictionary *userDic = (NSDictionary *)[cache objectForKey:KUserModelCache];
    if (userDic) {
        self.curUserInfo = [HRZUserInfo modelWithJSON:userDic];
        return YES;
    }
    return NO;
}

@end
